uniform sampler2D region1, region2, region3, region4;
varying vec3 texCoord;
uniform vec4 regionD1, regionD2, regionD3, regionD4;

vec4 GenerateTerrainColor()
{
    vec4 terrainColor = vec4(0.0, 0.0, 0.0, 1.0);
    float regionWeight = 0.0;

    // Terrain region 1.
    regionWeight = (regionD1.z - abs(texCoord.z - regionD1.y))*regionD1.w;
    regionWeight = max(0.0, regionWeight);
    terrainColor += regionWeight * texture2D(region1, texCoord.xy);

    // Terrain region 2.
    regionWeight = (regionD2.z - abs(texCoord.z - regionD2.y))*regionD2.w;
    regionWeight = max(0.0, regionWeight);
    terrainColor += regionWeight * texture2D(region2, texCoord.xy);

    // Terrain region 3.
    regionWeight = (regionD3.z - abs(texCoord.z - regionD3.y))*regionD3.w;
    regionWeight = max(0.0, regionWeight);
    terrainColor += regionWeight * texture2D(region3, texCoord.xy);

    // Terrain region 4.
    regionWeight = (regionD4.z - abs(texCoord.z - regionD4.y))*regionD4.w;
    regionWeight = max(0.0, regionWeight);
    terrainColor += regionWeight * texture2D(region4, texCoord.xy);

    return terrainColor;
}


void main()
{
	// create fog
	const float LOG2 = 1.442695;
	float z = clamp(gl_FragCoord.z / gl_FragCoord.w - gl_Fog.start, 0.0, 1000000000000.0);
	float fogFactor = exp2( -gl_Fog.density *
					   gl_Fog.density *
					   z *
					   z *
					   LOG2 );
	fogFactor = clamp(fogFactor, 0.0, 1.0);
	vec4 texFactor = GenerateTerrainColor();
	gl_FragColor = mix(gl_Fog.color, gl_Color*texFactor, fogFactor );

}
